/*
 * @Descripttion:
 * @version:
 * @Author: yuanliutech
 * @Date: 2022-11-30 09:18:03
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2025-02-10 17:35:35
 */
import router from "../../router/index";
import { reqLogin, reqUserInfo, reqSmsLogin, reqGetById } from "@api/api.js";
import asc from "@utils/asc.js";
import secretAES from "@/utils/encryption"; //前端加解密
import { initDynamicRoutes } from "@router"; //动态路由引入
import { encrypt, decrypt } from "@/utils/jsencrypt";

import { msgWarning } from "@plugins/modal.js";
import { Notification } from "element-ui";

let AES = new secretAES();
const user = {
    state: {
        isExpire: "", //账号是否到期

        // 前端解密
        permissions: JSON.parse(window.sessionStorage.getItem("permissions")) || [], //权限菜单
        userId: JSON.parse(decrypt(window.sessionStorage.getItem("userId"))) || "", //存储用户主键id
        userName: JSON.parse(decrypt(window.sessionStorage.getItem("userName"))) || "", //存储用户名称
        mobile: JSON.parse(decrypt(window.sessionStorage.getItem("mobile"))) || "", //存储用户手机
        nickName: JSON.parse(decrypt(window.sessionStorage.getItem("nickName"))) || "", //存储用户昵称
        avatarUrl: JSON.parse(decrypt(window.sessionStorage.getItem("avatarUrl"))) || "", //头像
        roleName: JSON.parse(decrypt(window.sessionStorage.getItem("roleName"))) || "", //角色名称
        roleDescription: JSON.parse(decrypt(window.sessionStorage.getItem("roleDescription"))) ||
            "", //角色名称描述
        roleId: JSON.parse(decrypt(window.sessionStorage.getItem("roleId"))) || "", //角色id
        tenantId: JSON.parse(decrypt(window.sessionStorage.getItem("tenantId"))) || "", //租户id
        tenantName: JSON.parse(decrypt(window.sessionStorage.getItem("tenantName"))) || "", //租户名称
        avatar: JSON.parse(decrypt(window.sessionStorage.getItem("avatar"))) || "", //头像
        siteName: JSON.parse(decrypt(window.sessionStorage.getItem("siteName"))) || "", //站点名称
        siteLogo: JSON.parse(decrypt(window.sessionStorage.getItem("siteLogo"))) || "", //站点logo
        dataVLogo: JSON.parse(decrypt(window.sessionStorage.getItem("dataVLogo"))) || "", //大屏logo

        orgId: window.sessionStorage.getItem("orgId") || "", //单位机构id
        orgName: window.sessionStorage.getItem("orgName") || "", //单位机构名称
        parkId: window.sessionStorage.getItem("parkId") || "", //园区id

        isExsistMap: false,

        deviceInfo: JSON.parse(window.sessionStorage.getItem("deviceInfo")) || [], //设备信息
    },

    mutations: {
        saveIsExpire(state, flag) {
            state.isExpire = flag;
        },
        // 存储登录用户id
        saveUserId(state, id) {
            const idInfo = encrypt(JSON.stringify(id)); //加密
            state.userId = id;
            window.sessionStorage.setItem("userId", idInfo);
        },
        // 存储登录用户名称
        saveUserName(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.userName = name;
            window.sessionStorage.setItem("userName", nameInfo);
        },
        // 存储登录用户手机
        saveMobile(state, mobile) {
            const mobileInfo = encrypt(JSON.stringify(mobile));
            state.mobile = mobile;
            window.sessionStorage.setItem("mobile", mobileInfo);
        },
        // 存储登录用户昵称
        saveNickName(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.nickName = name;
            window.sessionStorage.setItem("nickName", nameInfo);
        },
        // 存储登录用户头像
        saveAvatarUrl(state, data) {
            const dataInfo = encrypt(JSON.stringify(data));
            state.avatarUrl = data;
            window.sessionStorage.setItem("avatarUrl", dataInfo);
        },
        // 存储登录用户角色名称
        saveRoleName(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.roleName = name;
            window.sessionStorage.setItem("roleName", nameInfo);
        },
        // 存储登录用户角色名称
        saveroleDescription(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.roleDescription = name;
            window.sessionStorage.setItem("roleDescription", nameInfo);
        },
        // 存储登录用户角色Id
        saveRoleId(state, id) {
            const idInfo = encrypt(JSON.stringify(id));
            state.roleId = id;
            window.sessionStorage.setItem("roleId", idInfo);
        },
        // 存储登录用户权限菜单
        savePermissions(state, permissions) {
            // const permissionsInfo = encrypt(JSON.stringify(permissions));//可能长度太长加密会失败
            state.permissions = permissions;
            window.sessionStorage.setItem("permissions", JSON.stringify(permissions));
        },
        // 存储租户id
        saveTenantId(state, id) {
            const idInfo = encrypt(JSON.stringify(id));
            state.tenantId = id;
            window.sessionStorage.setItem("tenantId", idInfo);
        },
        // 存储租户名称
        saveTenantName(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.tenantName = name;
            window.sessionStorage.setItem("tenantName", nameInfo);
        },
        // 存储单位机构id
        saveOrgId(state, id) {
            state.orgId = id;
            window.sessionStorage.setItem("orgId", id);
        },
        // 存储单位机构名称
        saveOrgName(state, name) {
            state.orgName = name;
            window.sessionStorage.setItem("orgName", name);
        },
        // 站点名称
        saveSiteName(state, siteName) {
            const siteNameInfo = encrypt(JSON.stringify(siteName));
            state.siteName = siteName;
            window.sessionStorage.setItem("siteName", siteNameInfo);
        },
        // 站点logo
        saveSiteLogo(state, siteLogo) {
            const siteLogoInfo = encrypt(JSON.stringify(siteLogo));
            state.siteLogo = siteLogo;
            window.sessionStorage.setItem("siteLogo", siteLogoInfo);
        },
        // 大屏logo
        saveDataVLogo(state, dataVLogo) {
            const siteLogoInfo = encrypt(JSON.stringify(dataVLogo));
            state.dataVLogo = dataVLogo;
            window.sessionStorage.setItem("dataVLogo", siteLogoInfo);
        },
        saveAvatar(state, name) {
            const nameInfo = encrypt(JSON.stringify(name));
            state.avatar = name;
            window.sessionStorage.setItem("avatar", nameInfo);
        },
        // 存储园区id
        saveParkId(state, id) {
            state.parkId = id;
            window.sessionStorage.setItem("parkId", id);
        },
        // 地图
        saveIsExsitMap(state, val) {
            state.isExsistMap = val;
        },
        // 设备信息
        saveDeviceInfo(state, deviceInfo) {
            state.deviceInfo = deviceInfo;
            window.sessionStorage.setItem("deviceInfo", JSON.stringify(deviceInfo));
        },
    },

    actions: {
        // 登录
        Login({ commit }, info) {
            return new Promise(async(resolve, reject) => {
                // console.log(info);
                let res = "";
                if (info.password) {
                    // 密码登录
                    res = await reqLogin(AES.encryptionAES(JSON.stringify(info)));
                    //   if (res.code == 11133) {
                    //     this.$alert(res.message, "温馨提示", {
                    //       confirmButtonText: "确定",
                    //       type: "warning",
                    //     });
                    //     reject(res);
                    //     return;
                    //   }
                    if (res.code !== 20000) {
                        reject(res);
                        return;
                    }
                } else {
                    // 短信登录
                    res = await reqSmsLogin(info);
                    if (res.code !== 20000) {
                        reject(res);
                        return;
                    }
                }
                // resolve(res);
                sessionStorage.setItem("token", asc.encrypt(res.data.row.token));
                commit("saveIsExpire", res.data.row.isExpire);
                // 根据id查询个人用户信息
                this.dispatch("GetUserInfo", res.data.row.id).then((result) => {
                    // console.log(result, "result");
                    resolve(result);
                });
            });
        },
        // 根据id查询个人用户信息
        async GetUserInfo({ commit }, id) {
            return new Promise(async(resolve, reject) => {
                const res = await reqUserInfo(id); 
                if (res.code !== 20000) return msgWarning(res.message);
                let { rows } = res.data;
                // console.log(rows.tenantId);
                // Message.warning('账号未加入任何租户，不允许登录平台！')
                // 小程序注册的用户没加入到单位不允许登录平台
                if (rows.tenantId == 0 && rows.role.name == "ORG_ADMIN")
                    return Notification({
                        title: "温馨提示",
                        message: "账号未加入任何租户，不允许登录平台！",
                        type: "warning",
                    });
                // 给导航菜单排序 (不支持二级菜单排序)
                function compare(sort) {
                    return function(a, b) {
                        var value1 = a[sort];
                        var value2 = b[sort];
                        return value1 - value2;
                    };
                }
                let permissionsResult = rows.permissions.sort(compare("sort"));

                // 存储用户信息
                commit("saveUserId", rows.id);
                commit("saveUserName", rows.username);
                commit("saveMobile", rows.mobile);
                // commit("saveMobile", AES.encryptionAES(JSON.stringify(rows.mobile)));
                commit("saveNickName", rows.nickname);
                commit("saveAvatar", rows.avatar);
                commit("saveRoleName", rows.role.name);
                commit("saveroleDescription", rows.role.description);
                commit("saveRoleId", rows.role.id);
                commit("savePermissions", permissionsResult); //权限
                if (rows.tenantId) {
                    commit("saveTenantId", rows.tenantId);
                    commit("saveTenantName", rows.tenantName);
                }
                if (rows.orgId) {
                    commit("saveOrgId", rows.orgId);
                    commit("saveOrgName", rows.orgName);
                }
                if (rows.parkId) {
                    commit("saveParkId", rows.parkId);
                }
                if (rows.role.name == "TENANT_ADMIN" || rows.role.name == "ORG_ADMIN" || rows.role.name == "UNIT_ADMIN" || rows.role.name == "INSTERALL_USER") {
                    // console.log(rows.tenantId);
                    const res2 = await reqGetById(rows.tenantId);
                    // console.log(res2);
                    if (res2.code !== 20000) return msgWarning(res2.message);
                    commit("saveSiteName", res2.data.row.siteName);
                    commit("saveSiteLogo", res2.data.row.siteLogo);
                    commit("saveDataVLogo", res2.data.row.dataVLogo);
                }

                initDynamicRoutes(); //动态路由添加
                // 登录判断角色
                // console.log(rows);
                resolve(rows);
                return;
                // // 判断是不是超级管理员
                if (rows.role.name == "SUPER_ADMIN") {
                    router.replace({
                        path: "/system/member",
                    });
                    return;
                }
                // 系统运维
                if (rows.role.name == "PLATFORM_ADMIN") {
                    router.replace({
                        path: "/tenant/list",
                    });
                    return;
                }
                // 租户管理员 || 单位管理员
                if (rows.role.name == "TENANT_ADMIN" || rows.role.name == "ORG_ADMIN") {
                    // router.replace({
                    //     path: "/org/list"
                    // });
                    router.replace({
                        path: "/datav",
                    });
                    return;
                }
                router.replace({
                    path: "/",
                });
            });
        },

        // 获取用户信息
    },
};

export default user;